/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.stateless;

import entity.Credit;
import entity.Customer;
import entity.Invoice;
import entity.Payment;
import entity.PurchaseItem;
import entity.Receipt;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Wx
 */
@Stateless
public class CreditSessionBean implements CreditSessionBeanLocal, CreditSessionBeanRemote {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void updateInvoice(Long id, String status) {
        Invoice invoice = entityManager.find(Invoice.class, id);

        invoice.setStatus(status);

        entityManager.persist(invoice);
        entityManager.flush();
    }

    @Override
    public Receipt getReceipt(Long paymentId) {
        Query query = entityManager.createQuery("SELECT r FROM Receipt r");

        for (Object o : query.getResultList()) {
            Receipt r = (Receipt) o;

            if (r.getPayment().getId() == paymentId) {
                return r;
            }
        }

        return null;
    }

    @Override
    public Invoice getInvoice(Long purchaseItemId, String status, String type) {
        Query query = entityManager.createQuery("SELECT i FROM Invoice i WHERE i.status = :instatus and i.type = :intype");
        query.setParameter("instatus", status);
        query.setParameter("intype", type);

        for (Object o : query.getResultList()) {
            Invoice i = (Invoice) o;

            if (i.getPurchaseItem().getId() == purchaseItemId) {
                return i;
            }
        }

        return null;
    }

    @Override
    public Invoice getInvoice(Long purchaseItemId, String status) {
        Query query = entityManager.createQuery("SELECT i FROM Invoice i WHERE i.status = :instatus");
        query.setParameter("instatus", status);

        for (Object o : query.getResultList()) {
            Invoice i = (Invoice) o;

            if (i.getPurchaseItem().getId() == purchaseItemId) {
                return i;
            }
        }

        return null;
    }

    @Override
    public List<Invoice> getInvoices(Long purchaseItemId) {
        Query query = entityManager.createQuery("SELECT i FROM Invoice i");
        List<Invoice> invoices = new ArrayList<Invoice>();

        for (Object o : query.getResultList()) {
            Invoice i = (Invoice) o;

            if (i.getPurchaseItem().getId() == purchaseItemId) {
                invoices.add(i);
            }
        }

        return invoices;
    }

    @Override
    public void addInvoice(Invoice invoice) {
        PurchaseItem temp = entityManager.find(PurchaseItem.class, invoice.getPurchaseItem().getId());

        invoice.setPurchaseItem(temp);

        entityManager.persist(invoice);
        entityManager.flush();
    }

    @Override
    public void addCredit(Long customerId, Credit credit) {
        Customer temp = entityManager.find(Customer.class, customerId);

        temp.setCredit(credit);

        entityManager.persist(temp);
        entityManager.flush();
    }

    @Override
    public void updateCredit(Long creditId, Invoice invoice) {
        Credit credit = entityManager.find(Credit.class, creditId);
        List<Invoice> invoices = credit.getInvoices();

        invoices.add(invoice);
        credit.setInvoices(invoices);

        entityManager.persist(credit);
    }

    @Override
    public void updateCredit(Long creditId, Credit credit) {
        Credit temp = entityManager.find(Credit.class, creditId);

        temp.setCreditRank(credit.getCreditRank());
        temp.setCreditScore(credit.getCreditScore());
        temp.setPaymentsPaidLate30to59(credit.getPaymentsPaidLate30to59());
        temp.setPaymentsPaidLate60to89(credit.getPaymentsPaidLate60to89());
        temp.setPaymentsPaidLaterThan90(credit.getPaymentsPaidLaterThan90());
        temp.setPaymentsPaidLessThan30(credit.getPaymentsPaidLessThan30());
        temp.setAccountsPayable(credit.getAccountsPayable());
        temp.setOutstandingScore(credit.getOutstandingScore());
        temp.setPaymentScore(credit.getPaymentScore());
        temp.setRelationshipScore(credit.getRelationshipScore());
        temp.setRemark(credit.getRemark());
        temp.setTotalAmount(credit.getTotalAmount());
        temp.setTotalPayments(credit.getTotalPayments());
        temp.setYearsInBusiness(credit.getYearsInBusiness());
        temp.setYearsOfDealings(credit.getYearsOfDealings());
        temp.setCreditLimit(credit.getCreditLimit());
        temp.setDeposit(credit.getDeposit());
        temp.setBalance(credit.getBalance());
        temp.setCreditRate(credit.getCreditRate());

        entityManager.persist(temp);
        entityManager.flush();
    }

    @Override
    public void updatePurchaseItem(Long purchaseItemId, Double outstandingAmount, String status) {
        PurchaseItem purchaseItem = entityManager.find(PurchaseItem.class, purchaseItemId);

        purchaseItem.setOutstandingAmount(outstandingAmount);
        purchaseItem.setStatus(status);

        entityManager.persist(purchaseItem);
        entityManager.flush();
    }

    @Override
    public void updatePayment(Long id, String status) {
        Query query = entityManager.createQuery("SELECT p FROM Payment p");

        Payment payment = null;
        for (Object o : query.getResultList()) {
            payment = (Payment) o;

            if (payment.getInvoice().getId() == id) {
                break;
            }
        }

        payment.setStatus(status);

        entityManager.persist(payment);
        entityManager.flush();
    }

    @Override
    public void addPayment(Long invoiceId, Double amountPaid, Double balanceUsed, String status) {
        Calendar cal = Calendar.getInstance();
        Timestamp ts = new Timestamp(cal.getTime().getTime());

        Invoice invoice = entityManager.find(Invoice.class, invoiceId);

        Payment payment = new Payment(ts, amountPaid, balanceUsed, invoice, status);

        entityManager.persist(payment);
        entityManager.flush();
    }

    @Override
    public void addReceipt(Long paymentId, Double amountPaid, String status) {
        Calendar cal = Calendar.getInstance();
        Timestamp ts = new Timestamp(cal.getTime().getTime());

        Payment payment = entityManager.find(Payment.class, paymentId);

        Receipt receipt = new Receipt(ts, amountPaid, payment, status);

//        updateCredit(creditId, receipt);
        entityManager.persist(receipt);
        entityManager.flush();
    }

    @Override
    public Payment getPayment(Long invoiceId) {
        Query query = entityManager.createQuery("SELECT p FROM Payment p");

        for (Object o : query.getResultList()) {
            Payment p = (Payment) o;

            if (p.getInvoice().getId() == invoiceId) {
                return p;
            }
        }

        return null;
    }
}
